package com.ai.dmc.index.base.init;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.ai.dmc.cache.redis.client.dao.impl.RedisClientDaoImpl;
import com.ai.dmc.cache.redis.client.service.IRedisClientService;
import com.ai.dmc.index.common.data.PubConstant;
import com.ai.dmc.index.intf.service.cacheConfig.ICacheConfigService;
import com.alibaba.fastjson.JSON;

/**
 * 
* Title： 缓存数据系统启动初始化Bean <p>
* Description： 在系统启动时加载缓存配置表数据，将配置的sql执行结果放到缓存中 <p>
* Copyright：Copyright (c) 2009<p>
* Company：亚信智慧数据（中国）有限公司<p>
* @author chensen, 2016年1月11日<p>
* @version 1.0
 */
public class CacheDataInitBean implements InitializingBean{
	private static final Logger logger = LoggerFactory.getLogger(CacheDataInitBean.class);
	
	private ICacheConfigService cacheConfigService;
	private IRedisClientService redisClientService;
	
	public void setCacheConfigService(ICacheConfigService cacheConfigService) {
		this.cacheConfigService = cacheConfigService;
	}

	public void setRedisClientService(IRedisClientService redisClientService) {
		this.redisClientService = redisClientService;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		//缓存数据库配置数据
		cacheConfigData();
		//缓存一些配置表的数据
		cacheTableData();
	}
	
	/**
	 * 缓存数据库配置数据
	 */
	private void cacheConfigData(){
		List<Map<String, String>> cacheConfigInfoList = cacheConfigService.getCacheConfigInfo();
		if(cacheConfigInfoList != null && cacheConfigInfoList.size() > 0){
			for (Map<String, String> configMap : cacheConfigInfoList) {
				String cacheKey = configMap.get("cacheKey");
				String cacheSql = configMap.get("cacheSql");
				if(cacheSql != null && !"".equals(cacheSql)){
					List<Map<String, Object>> cacheDataList = cacheConfigService.executeSql(cacheSql);
					String cacheValue = JSON.toJSONString(cacheDataList);
					redisClientService.set(cacheKey, cacheValue);
					logger.info("系统初始化加载缓存，"+"cacheKey:"+cacheKey+",cacheValue:"+cacheValue);
				}
			}
		}
		
		List<Map<String, Object>> cacheConfigInfoDynicList = cacheConfigService.getCacheConfigInfoDynic();
		if(cacheConfigInfoDynicList != null && cacheConfigInfoDynicList.size() > 0){
			String json = JSON.toJSONString(cacheConfigInfoDynicList);
			String key = PubConstant.SQL_IDS;
			redisClientService.set(key, json);
		}
	}
	
	/**
	 * 缓存一些配置表的数据
	 */
	private void cacheTableData() {
		// TODO Auto-generated method stub
		
	}
}
